from system.object import Object
from system.eventServer import eventServer

class Editor(Object):
    def __init__(self, parent, type = None, name = None):
        Object.__init__(self, parent, type, name)
        
        self.load("editorMenu")
        
        fileObjects = ['frame','saveButton','loadButton','clearButton','fileText','drawRect','renderTypePullDown','colorPullDown','deleteButton','endButton','addHardpointButton','removeHardpointButton']
        
        for name in fileObjects:
            self.__dict__[name] = self.search("name",name,False)
            assert self.__dict__[name], "editorMenu must have a %s" % name
       
        self.gfx = self.drawRect.addChild("gfx")
        self.gfx.setVar("renderOp2d","sceneNode")
        self.gfx.setVar("hardpoints",[])
        
        self.currentLine = None
        self.justAdded = False
        self.addingHardpoint = False
        
        self.HardpointCircles = self.drawRect.addChild("HardpointCircles")
        
        eventServer.register("buttonClicked",self.buttonClicked)
        eventServer.register("mouseButtonDown",self.mouseButtonDown)
        eventServer.register("pullDownSelect",self.pullDownSelect)
        eventServer.register("mouseMotion",self.mouseMotion)
        
    def mouseMotion(self, cmd, args):
        self.mouseLineUpdate(args['x'],args['y'])
        
    def mouseLineUpdate(self, x, y):
        if self.currentLine:
            if not self.justAdded:
                self.removePoint()
            self.justAdded = False
            
            if self.currentLine:
                self.currentLine.getVar("points").append(self.transformMouse(x,y))
        
    def removePoint(self):
        if self.currentLine:
            self.currentLine.setVar("points",self.currentLine.getVar("points")[:-1])
            if not self.currentLine.getVar("points"):
                self.currentLine = None
        
    def endLine(self):
        if not self.justAdded:
            self.removePoint()
        
        self.currentLine = None
        
    def pullDownSelect(self, cmd, args):
        if args['path'] in [self.renderTypePullDown.getVar("path"), self.colorPullDown.getVar("path")]:
            self.endLine()
        
    def mouseButtonDown(self, cmd, args):
        if args['button'] == 1:
            
            if self.addingHardpoint:
                x,y = self.transformMouse(args['x'],args['y'])
                if x > 0 and x < 1 and y > 0 and y < 1:
                    print "add Hardpoint", x, y
                    self.gfx.getVar("hardpoints").append((x,y))
                    self.addingHardpoint = False
                    
                    self.updateHardpointCircles()
                    
            else:
                if not self.currentLine:
                    self.currentLine = self.gfx.addChild("line")
                    self.currentLine.setVar("renderOp2d","custom")
                    self.currentLine.setVar("renderType",self.renderTypePullDown.getVar("selection"))
                    self.currentLine.setVar("color",self.makeColor(self.colorPullDown.getVar("selection")))
                    self.currentLine.setVar("points",[])
                
                x,y = self.transformMouse(args['x'],args['y'])
                if x > 0 and x < 1 and y > 0 and y < 1:
                    if self.currentLine.getVar("points"):
                        self.removePoint()
                    self.currentLine.getVar("points").append((x,y))
                    self.justAdded = True
                
        #elif args['button'] == 2:
            #if not self.justAdded:
                #self.removePoint()
            #self.removePoint()
                
        #elif args['button'] == 3:
            #self.endLine()
            
        self.mouseLineUpdate(args['x'],args['y'])
        
    def updateHardpointCircles(self):
        self.HardpointCircles.clearChildren()
        
        for i, (x,y) in enumerate(self.gfx.getVar("hardpoints")):
            circle = self.HardpointCircles.addChild("circle")
            circle.setVar("renderOp2d","circle")
            circle.setVar("color",(1,0,0))
            circle.setVar("pos",(x,y))
            circle.setVar("scale",(0.05,0.05))
            circle.setVar("filled",False)
            
            text = circle.addChild("text")
            text.setVar("renderOp2d","text")
            text.setVar("text",str(i))
        
    def makeColor(self, name):
        colorDict = {"white":(1,1,1),"black":(0,0,0),"red":(1,0,0),"blue":(0,0,1),"green":(0,1,0)}
        if colorDict.has_key(name):
            return colorDict[name]
        else:
            return (1,1,1)
            
    def transformMouse(self, x, y):
        framePosx, framePosy = self.frame.getVar("pos")
        frameScalex, frameScaley = self.frame.getVar("scale")
        
        drawRectPosx, drawRectPosy = self.drawRect.getVar("pos")
        drawRectScalex, drawRectScaley = self.drawRect.getVar("scale")
        
        drawRectNetPosx = framePosx + drawRectPosx * frameScalex
        drawRectNetPosy = framePosy + drawRectPosy * frameScaley
        
        drawRectNetScalex = drawRectScalex * frameScalex
        drawRectNetScaley = drawRectScaley * frameScaley
        
        pointx = (x - drawRectNetPosx) / drawRectNetScalex
        pointy = (y - drawRectNetPosy) / drawRectNetScaley
        
        return pointx, pointy
            
    def buttonClicked(self, cmd, args):
        if args['path'] == self.saveButton.getVar("path"):
            self.fileText.getVar("text").lstrip('^h')
            for name in self.gfx.children.keys():
                if not self.gfx.getChild(name).getVar("points"):
                    self.gfx.removeChild(name)
            self.gfx.save(self.fileText.getVar("text"))
            
        elif args['path'] == self.loadButton.getVar("path"):
            self.gfx.load(self.fileText.getVar("text"))
            
        elif args['path'] == self.clearButton.getVar("path"):
            self.gfx.clearChildren()
            
        elif args['path'] == self.deleteButton.getVar("path"):
            self.removePoint()
            
        elif args['path'] == self.endButton.getVar("path"):
            self.endLine()
            
        elif args['path'] == self.addHardpointButton.getVar("path"):
            self.addingHardpoint = True
            
        elif args['path'] == self.removeHardpointButton.getVar("path"):
            self.gfx.setVar("hardpoints",self.gfx.getVar("hardpoints")[:-1])

        self.updateHardpointCircles()
        self.mouseLineUpdate(args['x'],args['y'])
